import {useRef, useEffect} from "react";
import {useReactive} from "ahooks";

export default function SeatSelector() {

    const ele = useRef()

    const rows = 10;
    const cols = 10;
    const gap = 10;
    const seatSize = 40;

    const stauts = useReactive(new Array(rows).fill(null).map(() => new Array(cols).fill(false)))

    const draw = () => {
        const canvas = ele.current;
        const ctx = canvas.getContext('2d');

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                let x = col * (gap + seatSize);
                let y = row * (gap + seatSize);

                ctx.fillStyle = stauts[col][row] ? 'red' : '#ccc';
                ctx.fillRect(x, y, seatSize, seatSize);
            }
        }
    }

    const handleClick = (e) => {
        const canvas = ele.current;
        const rect = canvas.getBoundingClientRect()
        const scaleX = canvas.width / rect.width;
        const scaleY = canvas.height / rect.height;

        const x = (e.clientX - rect.left) * scaleX
        const y = (e.clientY - rect.top) * scaleY

        const col = Math.floor(x / (seatSize + gap)) + 1
        const row = Math.floor(y / (seatSize + gap)) + 1

        const notOnGapX = x > (col - 1) * (seatSize + gap) && x < col * (seatSize + gap) - gap
        const notOnGapY = y > (row - 1) * (seatSize + gap) && y < row * (seatSize + gap) - gap
        if (!notOnGapY || !notOnGapX) return
        stauts[col - 1][row - 1] = !stauts[col - 1][row - 1]

    }

    useEffect(() => {
        draw();
    }, [draw])


    return (
        <div>
            <canvas width="490" height="490" ref={ele}
                    onClick={(e) => handleClick(e)}></canvas>
        </div>
    )
}